package org.hackystat.linkedservicedata.ui;

import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 * Provide log-in.
 *
 * @author Myriam Leggieri.
 *
 */
public class SignInPanel extends JPanel implements KeyListener, ActionListener {
  private static final long serialVersionUID = 4268685212560864275L;

  private JLayeredPane layeredPane;

  private JLabel userLabel;

  private JLabel passwordLabel;

  private JTextField userText;

  private JPasswordField passwordText;

  private JButton loginButton;

  private JButton logoutButton;

  private JButton cancelButton;

  private String user = null;

  private String password = null;

  private JPanel panel;

  private LinkedServiceDataUI mainframe = null;

  public SignInPanel(LinkedServiceDataUI mainframe) {
    super();
    this.mainframe = mainframe;
    refresh();
  }

  public void refresh() {
    this.removeAll();
    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.setBackground(Color.WHITE);
    layeredPane = new JLayeredPane();
    Point origin = null;

    if (passwordLabel == null) {
      passwordLabel = new JLabel();
      passwordLabel.setDisplayedMnemonic(KeyEvent.VK_P);
      passwordLabel.setForeground(Color.BLUE);
      passwordLabel.setText("Password:");
      passwordLabel.setFont(new Font("Dialog", java.awt.Font.BOLD, 20));
      origin = new Point(640, 200);
      passwordLabel.setBounds(origin.x, origin.y, 120, 100);
    }
    layeredPane.add(passwordLabel);

    if (userText == null) {
      userText = new JTextField(10);
      userText.setFont(new Font("Dialog", java.awt.Font.PLAIN, 18));
      origin = new Point(750, 160);
      userText.setBounds(origin.x, origin.y, 300, 25);
    }
    userText.setText(mainframe.loggedUser);
    userText.setEditable(!mainframe.isLogged);
    layeredPane.add(userText);

    if (userLabel == null) {
      userLabel = new JLabel();
      userLabel.setText("Email:");
      userLabel.setDisplayedMnemonic(KeyEvent.VK_U);
      userLabel.setForeground(Color.BLUE);
      userLabel.setFont(new Font("Dialog", java.awt.Font.BOLD, 20));
      userLabel.setLabelFor(userText);
      origin = new Point(640, 125);
      userLabel.setBounds(origin.x, origin.y, 100, 100);
    }
    layeredPane.add(userLabel);

    if (passwordText == null) {
      passwordText = new JPasswordField();
      passwordLabel.setLabelFor(passwordText);
      passwordText.setFont(new Font("Dialog", java.awt.Font.PLAIN, 18));
      origin = new Point(750, 235);
      passwordText.setBounds(origin.x, origin.y, 300, 25);
    }
    passwordText.setText(mainframe.loggedPassw);
    passwordText.setEditable(!mainframe.isLogged);
    layeredPane.add(passwordText);

    if (!mainframe.isLogged) {
      if (loginButton == null) {
        loginButton = new JButton();
        loginButton.setMnemonic(KeyEvent.VK_I);
        loginButton.setFont(new Font("Dialog", java.awt.Font.BOLD, 18));
        loginButton.setText("Login");
        loginButton.addActionListener(this);
        origin = new Point(750, 430);
        loginButton.setBounds(origin.x, origin.y, 100, 30);
      }
      layeredPane.add(loginButton);
      if (cancelButton == null) {
        cancelButton = new JButton();
        cancelButton.setMnemonic(KeyEvent.VK_D);
        cancelButton.setFont(new Font("Dialog", java.awt.Font.BOLD, 18));
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(this);
        origin = new Point(900, 430);
        cancelButton.setBounds(origin.x, origin.y, 100, 30);
      }
      layeredPane.add(cancelButton);
    }
    else {
      if (logoutButton == null) {
        logoutButton = new JButton();
        logoutButton.setMnemonic(KeyEvent.VK_O);
        logoutButton.setFont(new Font("Dialog", java.awt.Font.BOLD, 18));
        logoutButton.setText("Logout");
        logoutButton.addActionListener(this);
        origin = new Point(750, 430);
        logoutButton.setBounds(origin.x, origin.y, 130, 30);
      }
      layeredPane.add(logoutButton);
    }

    layeredPane.setBackground(Color.white);

    panel.add(layeredPane);
    panel.setPreferredSize(mainframe.subwinDimension);
    panel.setBackground(Color.white);
    this.add(panel);
    this.repaint();
    this.validate();
  }

  public void addComponent() {
    layeredPane.add(cancelButton, new Integer(1));
    layeredPane.add(loginButton, new Integer(1));
    layeredPane.add(passwordLabel, new Integer(1));
    layeredPane.add(userText, new Integer(1));
    layeredPane.add(userLabel, new Integer(1));
    layeredPane.add(passwordText, new Integer(1));
    userText.requestFocusInWindow();
  }

  private void resetForm() {
    userText.setText("");
    passwordText.setText("");
  }

  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = Start.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    }
    else {
      System.err.println("Couldn't find file: " + path);
      return null;
    }
  }

  /**
   * Check the correctness of the filled in values.
   *
   * @return true if the filled in values are correct.
   */
  private boolean checkField() {
    boolean ret = false;
    try {
      if ((userText.getText()).trim().compareTo("") == 0)
        throw new Exception("Missing user name.");
      if ((new String(passwordText.getPassword())).trim().compareTo("") == 0)
        throw new Exception("Missing password.");
      ret = true;
    }
    catch (Exception ex) {
      Toolkit.getDefaultToolkit().beep();
      JOptionPane.showMessageDialog(this, ex.getMessage(),
          "Hackystat - There are still empty fields.", JOptionPane.OK_CANCEL_OPTION);
      if ((userText.getText()).compareTo("") == 0)
        userText.requestFocusInWindow();
      if ((new String(passwordText.getPassword())).compareTo("") == 0)
        passwordText.requestFocusInWindow();
    }
    return ret;

  }

  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    if (source.equals(cancelButton)) {
      resetForm();
    }
    else if (source.equals(loginButton)) {
      if (checkField()) {
        user = userText.getText().trim();
        password = "";
        char[] pass = passwordText.getPassword();
        for (int i = 0; i < pass.length; i++) {
          password += pass[i];
        }
        try {
          mainframe.initLinkedServiceDataClient(user, password);
        }
        catch (Exception e1) {
          // e1.printStackTrace();
          JOptionPane.showMessageDialog(this, e1.getMessage(), "Hackystat - Error Message",
              JOptionPane.ERROR_MESSAGE);
          resetForm();
          userText.requestFocusInWindow();
          return;
        }
        mainframe.setLogged(true);
      }
      refresh();
    }
    else if (source.equals(logoutButton)) {
      mainframe.setLogged(false);
      refresh();
    }
  }

  @Override
  public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

  }

}
